import { View } from '@tarojs/components'
import React, { useState, useEffect } from 'react';
import { useDidHide } from '@tarojs/taro';
import './count-down.scss'
import { calcTime } from '../../utils/tools'

const CountDown: React.FC<{isLimited?: boolean;time: number;inDjs?:any;isBGColor?: boolean;}> = (props) => {
    const [timeInfo, setTimeInfo] = useState({
        dur: 0,
        day: '00',
        hour: '00',
        minute: '00',
        second: '00',
        month: '00',
        year: '00',
    })
    let timer: any;
    useEffect(() => {
        let nowTime = new Date().getTime()
        if(props.time - nowTime < 1000 && props.inDjs){
          props.inDjs()
        }
        timer = setInterval(() => {
            const times = calcTime(props.time, nowTime)
            setTimeInfo(times)
            nowTime = nowTime + 1000
            if(props.time - nowTime < 1000 && props.inDjs){
              props.inDjs()
            }
        }, 1000)
        return () => {
            clearInterval(timer)
        }
    }, [props.time])
    useDidHide(() => {
        clearInterval(timer)
    })
    return (
        <View className={`countDown ${props.isLimited && 'isLimited'}`}>
            <View className={props.isBGColor? 'sell-day':'timer-item number'}>{Number(timeInfo.day) > 999 ? 999 : timeInfo.day}</View>
            <View className={props.isBGColor?'timer-item text-new':'timer-item text'}>天</View>
            <View className={props.isBGColor? 'sell-end':'timer-item number'}>{timeInfo.hour}</View>
            <View className={props.isBGColor?'timer-item text-new':'timer-item text'}>{ !props.isLimited ? '时' : ':' }</View>
            <View className={props.isBGColor? 'sell-end':'timer-item number'}>{timeInfo.minute}</View>
            <View className={props.isBGColor?'timer-item text-new':'timer-item text'}>{ !props.isLimited ? '分' : ':' }</View>
            <View className={props.isBGColor? 'sell-end':'timer-item number'}>{timeInfo.second}</View>
            <View className={props.isBGColor?'timer-item text-new':'timer-item text'}>{ !props.isLimited ? '秒' : '' }</View>
        </View>
    )
}

export default CountDown
